﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fuse8.ContentManagementFramework.Domain.Commands;
using Fuse8.ContentManagementFramework.Domain.Commands.CommandParameters;
using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.ContentManagementFramework.SystemFacade.Common;
using Fuse8.DomainFramework.BusinessService;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.Domain;

namespace Fuse8.ContentManagementFramework.BizFacade.Services
{

    public interface ICmsSearchService
    {
        IEnumerable<CmsAdminSearchResult> Search(string searchQuery);
    }

    public class CmsSearchService<TEntity> : ICmsSearchService where TEntity : Int32EntityObject, new()
    {
        private Func<TEntity, CmsAdminSearchResult> _mapper;

        public CmsSearchService(Func<TEntity, CmsAdminSearchResult> mapper)
        {
            _mapper = mapper;
        }

        public virtual IEnumerable<CmsAdminSearchResult> Search(string searchQuery)
        {
            var service = new BusinessServiceFacade<TEntity, Int32>();

            var searchCommand = DependencyServiceLocator.Current.GetInstance<CmsEntitySearchCommand<TEntity>>();

            var parameter = new CmsEntitySearchCommandParameter { SearchQuery = searchQuery };

            SiteAwareEntityObjectMediator.SetSiteEntity(parameter);

            AdministrationAreaMediator.SetAreaFlag(parameter);

            searchCommand.ConfigureCommand(parameter);

            var results = service.Find(searchCommand);

            return results.Select(e => _mapper(e));
        }

    }
}
